<!-- 简易版购物车 -->
<template>
	<view>
		<checkbox-group @change="changeCheckbox">
			<view class="item" v-for="(item,index) in cart" :key="item.id">
				<checkbox :value="item.id" :checked="item.checked"></checkbox>
				<text class="title">{{item.name}}</text>
				<text class="price">￥{{item.price}}</text>
				<text class="del" @click="delItem(index)">删除</text>
			</view>
			
		</checkbox-group>
		<view class="sum">
			<checkbox @click="changeAll" :checked="allCheck"></checkbox>全选
			<view class="total">总计{{checkGroup.length}}个，总价格{{total}}元</view></view>
	</view>
</template>

<script setup>
	import {
		ref,computed,watch
	} from 'vue'
	const cart = ref([
		{id: '1',name: '小米',price: 123,checked:false},
		{id: '2',name: '华为',price: 234,checked:false},
		{id: '3',name: 'oppo',price: 345,checked:false},
		{id: '4',name: 'vivo',price: 456,checked:false}
	])
	const checkGroup = ref([])
	const allCheck = ref(false)
	//删除事件
	const delItem = (index)=>{
		cart.value.splice(index,1)
		checkGroup.value = cart.value.filter(item=>item.checked).map(item=>item.id)
	}
	
	//全选事件
	const changeAll = ()=>{
		allCheck.value = !allCheck.value
		cart.value =  cart.value.map((item)=>{
			return  {
				...item,
				checked:allCheck.value
			}
		})
		checkGroup.value = allCheck.value ?  cart.value.map(item=>item.id) : []
	}
	
	//单选事件
	const changeCheckbox = (e)=>{
		checkGroup.value = e.detail.value
		cart.value =  cart.value.map(item=>{
			return{
				...item,
				checked:checkGroup.value.includes(item.id)
			} 
		})
	}
	//计算价格
	const total = computed(()=>{
		return cart.value.filter(item=>item.checked).reduce((prev,current)=>prev+current.price,0)
	})
	
	watch(cart,()=>{
		allCheck.value = cart.value.every(item=>item.checked)
	})
</script>

<style lang="scss">
	.item {
		padding: 20rpx;
		.title {
			margin: 0 10rpx;
			font-size: 30rpx;
		}
		.price{
			margin:  0 10rpx;
		}
		.del {
			font-size: 30rpx;
			color: red;
			margin-left: 20rpx;
		}
	}
	.sum{
		margin-top: 30rpx;
		padding-left: 20rpx;
		display: flex;
		.total{
			margin-left: 200rpx;
		}
	}
</style>
